package com.majorty.mb.controller.response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

/**
 * 分页模板工具类
 * @author zhangshuai
 * @date 2019-09-22 22:52
 */
public class PageTemplateUtil {

    private static Logger logger = LoggerFactory.getLogger(PageTemplateUtil.class);

    /**
     * 处理分页参数
     * @param criteria
     * @param paginationResult
     * @param total
     * @param <T>
     */
    public static <T extends Pagination> void setPagination(T criteria, PaginationResult paginationResult, int total) {
        /** 方法参数检查 */
        if (null == criteria || !(criteria instanceof Pagination)) {
            logger.error("please check the method args！");
            throw new RuntimeException("please check the method args！");
        }

        /** 设置分页相关的参数 */
        Pagination reqPagination = (Pagination)criteria;
        /** 每页记录总数 */
        int limit = (reqPagination.getPageSize() == 0 ? total : reqPagination.getPageSize());
        if (limit > 0 && total > 0) {
            /**总页数 */
            int pages = (total % limit == 0) ? (total / limit) : (total / limit + 1);
            /**开始行号 */
            int startRow = 0;
            /**结束行号 */
            int endRow = 0;
            /** 查询最后一页 */
            if (reqPagination.getPageNum() == -1 || reqPagination.getPageNum()  == pages) {
                startRow = (pages - 1) * limit;
                endRow = startRow + (total % limit == 0 ? limit : (total % limit)) - 1;
            } else {
                startRow = (reqPagination.getPageNum() - 1) * limit;
                endRow = startRow + limit - 1;
            }
            reqPagination.setStartRow(startRow);
            reqPagination.setEndRow(endRow);
            reqPagination.setPages(pages);
            reqPagination.setTotal(total);
        } else {
            reqPagination.setStartRow(0);
            reqPagination.setEndRow(total-1);
            reqPagination.setPages(1);
            reqPagination.setTotal(total);
        }
        /** 把查询条件中计算好的分页信息copy到结果字段中,返回给前端*/
        BeanUtils.copyProperties(reqPagination, paginationResult);
    }
}
